package com.onefinger.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.onefinger.aspect.Cache;
import com.onefinger.aspect.Uncache;
import com.onefinger.domain.Language;
import com.onefinger.domain.Resource;
import com.onefinger.repository.GenericRepository;

public class ResourceService implements IResourceService {

	@Autowired
	GenericRepository<Resource> genericRepository; 
	
	@Autowired
	ILanguageService languageService;
	
	private Map<String, Map<String, String > > resources ;
	
	@Cache(cacheKey="resources", expireTime=0)
	public List<Resource> list() {
		return genericRepository.getList(Resource.class);
	}

	
	@Uncache(cacheKey="resources")
	public boolean save(Resource resource) {
		try {
			genericRepository.save(resource);
			languageService.updateVersion( resource.getLocale() );
			// force to init map of resources... not too fast but clean....
			resources = null;
		} catch (Exception e) {
			
			return false;
		}
		return true;
	}

	@Uncache(cacheKey="resources")
	public boolean remove(Resource resource) {
		try {
			genericRepository.remove(resource);
		} catch (Exception e) {
			
			return false;
		}
		return true;
	}


	@Override
	public String getLocale(String locale, String code) {
		
		if( resources == null )
		{
			initResources();
		}
		
		Map<String,String> mapLocale = resources.get(locale);
		if( mapLocale == null )
		{
			return code + " ( " + locale + " missing? )";
		}
		
		String value = mapLocale.get(code);
		if( value == null )
		{
			return code + " ( " + locale + " + " + code + " missing? )";
		}
		return value;
	}

	private void initResources() {

		resources = new HashMap<String, Map<String,String>>();
		
		List<Resource> list = list();
		
		for (Resource resource : list) {
			
			String localeName = resource.getLocale();
			
			Map<String, String> mapLocale = resources.get( localeName );
			
			if( mapLocale == null )
			{
				mapLocale = new HashMap<String, String>();
				resources.put( localeName, mapLocale );
			}
			
			mapLocale.put( resource.getCode(), resource.getValue() );
		}

	}
}
